import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Tag,
  Avatar,
  Input,
  Select,
  DatePicker,
  Typography,
  Row,
  Col,
  Modal,
  Timeline,
  message,
  Badge,
} from 'antd';
import {
  SearchOutlined,
  EyeOutlined,
  MessageOutlined,
  GiftOutlined,
  CalendarOutlined,
  UserOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { InteractionRecord } from '@/types';
import { formatDate, getAvatarUrl } from '@/utils';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

interface InteractionDetail extends InteractionRecord {
  userAInfo: {
    nickname: string;
    avatar?: string;
    age: number;
    gender: 'male' | 'female';
  };
  userBInfo: {
    nickname: string;
    avatar?: string;
    age: number;
    gender: 'male' | 'female';
  };
  duration?: number; // 互动持续时间（分钟）
  messageCount?: number; // 消息数量
}

const InteractionRecordPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [interactions, setInteractions] = useState<InteractionDetail[]>([]);
  const [selectedInteraction, setSelectedInteraction] = useState<InteractionDetail | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [filters, setFilters] = useState({
    keyword: '',
    type: 'all',
    status: 'all',
  });

  // Mock interaction data
  const mockInteractions: InteractionDetail[] = [
    {
      id: '1',
      userA: '1',
      userB: '2',
      userAInfo: {
        nickname: '李小花',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female1',
        age: 26,
        gender: 'female',
      },
      userBInfo: {
        nickname: '王明',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male1',
        age: 28,
        gender: 'male',
      },
      type: 'chat',
      content: '双方进行了深入的聊天交流',
      timestamp: '2024-01-20T14:25:00Z',
      status: 'active',
      duration: 45,
      messageCount: 23,
    },
    {
      id: '2',
      userA: '3',
      userB: '4',
      userAInfo: {
        nickname: '张丽',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female2',
        age: 24,
        gender: 'female',
      },
      userBInfo: {
        nickname: '陈志强',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male2',
        age: 30,
        gender: 'male',
      },
      type: 'gift',
      content: '用户A向用户B赠送了虚拟礼物',
      timestamp: '2024-01-19T16:45:00Z',
      status: 'active',
    },
    {
      id: '3',
      userA: '5',
      userB: '6',
      userAInfo: {
        nickname: '刘芳',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female3',
        age: 29,
        gender: 'female',
      },
      userBInfo: {
        nickname: '赵华',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male3',
        age: 32,
        gender: 'male',
      },
      type: 'meet',
      content: '双方约定线下见面',
      timestamp: '2024-01-18T11:30:00Z',
      status: 'ended',
    },
  ];

  const getTypeIcon = (type: string) => {
    const iconMap = {
      chat: <MessageOutlined style={{ color: '#1890ff' }} />,
      gift: <GiftOutlined style={{ color: '#eb2f96' }} />,
      meet: <CalendarOutlined style={{ color: '#52c41a' }} />,
    };
    return iconMap[type as keyof typeof iconMap] || <MessageOutlined />;
  };

  const getTypeTag = (type: string) => {
    const typeMap = {
      chat: { color: 'blue', text: '聊天' },
      gift: { color: 'pink', text: '礼物' },
      meet: { color: 'green', text: '见面' },
    };
    const config = typeMap[type as keyof typeof typeMap];
    return <Tag color={config?.color} icon={getTypeIcon(type)}>{config?.text}</Tag>;
  };

  const getStatusTag = (status: string) => {
    const statusMap = {
      active: { color: 'green', text: '进行中' },
      ended: { color: 'gray', text: '已结束' },
    };
    const config = statusMap[status as keyof typeof statusMap];
    return <Tag color={config?.color}>{config?.text}</Tag>;
  };

  const columns: ColumnsType<InteractionDetail> = [
    {
      title: '互动用户',
      key: 'users',
      width: 220,
      render: (_, record) => (
        <div>
          <Space style={{ marginBottom: '8px' }}>
            <Avatar
              size={32}
              src={getAvatarUrl(record.userAInfo.avatar, record.userAInfo.gender)}
              icon={<UserOutlined />}
            />
            <div>
              <Text strong>{record.userAInfo.nickname}</Text>
              <br />
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {record.userAInfo.age}岁 • {record.userAInfo.gender === 'male' ? '男' : '女'}
              </Text>
            </div>
          </Space>
          <div style={{ textAlign: 'center', margin: '4px 0' }}>
            <Text type="secondary" style={{ fontSize: '12px' }}>↔</Text>
          </div>
          <Space>
            <Avatar
              size={32}
              src={getAvatarUrl(record.userBInfo.avatar, record.userBInfo.gender)}
              icon={<UserOutlined />}
            />
            <div>
              <Text strong>{record.userBInfo.nickname}</Text>
              <br />
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {record.userBInfo.age}岁 • {record.userBInfo.gender === 'male' ? '男' : '女'}
              </Text>
            </div>
          </Space>
        </div>
      ),
    },
    {
      title: '互动类型',
      key: 'type',
      width: 100,
      render: (_, record) => getTypeTag(record.type),
      filters: [
        { text: '聊天', value: 'chat' },
        { text: '礼物', value: 'gift' },
        { text: '见面', value: 'meet' },
      ],
      onFilter: (value, record) => record.type === value,
    },
    {
      title: '互动详情',
      key: 'content',
      render: (_, record) => (
        <div>
          <Text>{record.content}</Text>
          {record.type === 'chat' && (
            <div style={{ marginTop: '4px' }}>
              <Space size={16}>
                {record.messageCount && (
                  <Badge count={record.messageCount} size="small">
                    <Text type="secondary" style={{ fontSize: '12px' }}>消息数</Text>
                  </Badge>
                )}
                {record.duration && (
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    持续 {record.duration} 分钟
                  </Text>
                )}
              </Space>
            </div>
          )}
        </div>
      ),
    },
    {
      title: '状态',
      key: 'status',
      width: 100,
      render: (_, record) => getStatusTag(record.status),
      filters: [
        { text: '进行中', value: 'active' },
        { text: '已结束', value: 'ended' },
      ],
      onFilter: (value, record) => record.status === value,
    },
    {
      title: '时间',
      key: 'timestamp',
      width: 160,
      render: (_, record) => formatDate(record.timestamp, 'MM-DD HH:mm'),
      sorter: (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => (
        <Space>
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
        </Space>
      ),
    },
  ];

  const handleViewDetail = (record: InteractionDetail) => {
    setSelectedInteraction(record);
    setDetailModalVisible(true);
  };

  const handleSearch = async () => {
    try {
      setLoading(true);
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 500));
      
      let filtered = mockInteractions;
      
      if (filters.keyword) {
        filtered = filtered.filter(record =>
          record.userAInfo.nickname.includes(filters.keyword) ||
          record.userBInfo.nickname.includes(filters.keyword) ||
          record.content.includes(filters.keyword)
        );
      }
      
      if (filters.type !== 'all') {
        filtered = filtered.filter(record => record.type === filters.type);
      }
      
      if (filters.status !== 'all') {
        filtered = filtered.filter(record => record.status === filters.status);
      }
      
      setInteractions(filtered);
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleExport = () => {
    message.info('正在导出互动记录...');
    // Simulate export
    setTimeout(() => {
      message.success('导出成功');
    }, 2000);
  };

  // Generate timeline data for detail modal
  const generateTimelineData = (interaction: InteractionDetail) => {
    const timeline = [
      {
        color: 'blue',
        children: (
          <div>
            <Text strong>互动开始</Text>
            <br />
            <Text type="secondary">{formatDate(interaction.timestamp)}</Text>
          </div>
        ),
      },
    ];

    if (interaction.type === 'chat' && interaction.messageCount) {
      timeline.push({
        color: 'green',
        children: (
          <div>
            <Text strong>活跃聊天</Text>
            <br />
            <Text type="secondary">共发送 {interaction.messageCount} 条消息</Text>
          </div>
        ),
      });
    }

    if (interaction.type === 'gift') {
      timeline.push({
        color: 'pink',
        children: (
          <div>
            <Text strong>礼物赠送</Text>
            <br />
            <Text type="secondary">虚拟礼物已送达</Text>
          </div>
        ),
      });
    }

    if (interaction.status === 'ended') {
      timeline.push({
        color: 'gray',
        children: (
          <div>
            <Text strong>互动结束</Text>
            <br />
            <Text type="secondary">双方结束了此次互动</Text>
          </div>
        ),
      });
    }

    return timeline;
  };

  useEffect(() => {
    handleSearch();
  }, []);

  return (
    <div className="page-container">
      <div className="page-header">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <Title level={4} className="page-title">互动记录</Title>
            <Text className="page-description">
              查看用户之间的互动记录，包括聊天、礼物赠送、见面约定等
            </Text>
          </div>
          <Button icon={<DownloadOutlined />} onClick={handleExport}>
            导出记录
          </Button>
        </div>
      </div>

      {/* Filters */}
      <Card style={{ marginBottom: '16px' }} bodyStyle={{ paddingBottom: '0' }}>
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={8} md={6}>
            <Input
              placeholder="搜索用户昵称或内容"
              prefix={<SearchOutlined />}
              value={filters.keyword}
              onChange={(e) => setFilters({ ...filters, keyword: e.target.value })}
              onPressEnter={handleSearch}
            />
          </Col>
          <Col xs={24} sm={8} md={4}>
            <Select
              placeholder="互动类型"
              value={filters.type}
              onChange={(value) => setFilters({ ...filters, type: value })}
              style={{ width: '100%' }}
            >
              <Select.Option value="all">全部类型</Select.Option>
              <Select.Option value="chat">聊天</Select.Option>
              <Select.Option value="gift">礼物</Select.Option>
              <Select.Option value="meet">见面</Select.Option>
            </Select>
          </Col>
          <Col xs={24} sm={8} md={4}>
            <Select
              placeholder="状态"
              value={filters.status}
              onChange={(value) => setFilters({ ...filters, status: value })}
              style={{ width: '100%' }}
            >
              <Select.Option value="all">全部状态</Select.Option>
              <Select.Option value="active">进行中</Select.Option>
              <Select.Option value="ended">已结束</Select.Option>
            </Select>
          </Col>
          <Col xs={24} sm={24} md={6}>
            <RangePicker
              placeholder={['开始时间', '结束时间']}
              style={{ width: '100%' }}
            />
          </Col>
          <Col xs={24} sm={24} md={4}>
            <Space>
              <Button type="primary" onClick={handleSearch} loading={loading}>
                搜索
              </Button>
              <Button onClick={() => setFilters({ keyword: '', type: 'all', status: 'all' })}>
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* Statistics Cards */}
      <Row gutter={[16, 16]} style={{ marginBottom: '16px' }}>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                {interactions.length}
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>总互动数</div>
            </div>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
                {interactions.filter(r => r.status === 'active').length}
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>进行中</div>
            </div>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#fa8c16' }}>
                {interactions.filter(r => r.type === 'chat').length}
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>聊天记录</div>
            </div>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#eb2f96' }}>
                {interactions.filter(r => r.type === 'meet').length}
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>见面约定</div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* Interactions Table */}
      <Card>
        <Table
          columns={columns}
          dataSource={interactions}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* Detail Modal */}
      <Modal
        title="互动详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={700}
      >
        {selectedInteraction && (
          <div>
            {/* Users Info */}
            <div style={{ textAlign: 'center', marginBottom: '24px' }}>
              <Space size={32}>
                <div>
                  <Avatar
                    size={64}
                    src={getAvatarUrl(selectedInteraction.userAInfo.avatar, selectedInteraction.userAInfo.gender)}
                    icon={<UserOutlined />}
                  />
                  <div style={{ marginTop: '8px' }}>
                    <Text strong>{selectedInteraction.userAInfo.nickname}</Text>
                    <br />
                    <Text type="secondary">
                      {selectedInteraction.userAInfo.age}岁 • {selectedInteraction.userAInfo.gender === 'male' ? '男' : '女'}
                    </Text>
                  </div>
                </div>
                
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                  {getTypeIcon(selectedInteraction.type)}
                  <div style={{ marginTop: '8px' }}>
                    {getTypeTag(selectedInteraction.type)}
                  </div>
                </div>
                
                <div>
                  <Avatar
                    size={64}
                    src={getAvatarUrl(selectedInteraction.userBInfo.avatar, selectedInteraction.userBInfo.gender)}
                    icon={<UserOutlined />}
                  />
                  <div style={{ marginTop: '8px' }}>
                    <Text strong>{selectedInteraction.userBInfo.nickname}</Text>
                    <br />
                    <Text type="secondary">
                      {selectedInteraction.userBInfo.age}岁 • {selectedInteraction.userBInfo.gender === 'male' ? '男' : '女'}
                    </Text>
                  </div>
                </div>
              </Space>
            </div>

            {/* Interaction Details */}
            <Row gutter={[24, 24]}>
              <Col span={12}>
                <Card title="基本信息" size="small">
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <div>
                      <Text strong>互动类型：</Text>
                      {getTypeTag(selectedInteraction.type)}
                    </div>
                    <div>
                      <Text strong>状态：</Text>
                      {getStatusTag(selectedInteraction.status)}
                    </div>
                    <div>
                      <Text strong>开始时间：</Text>
                      <Text>{formatDate(selectedInteraction.timestamp)}</Text>
                    </div>
                    {selectedInteraction.duration && (
                      <div>
                        <Text strong>持续时间：</Text>
                        <Text>{selectedInteraction.duration} 分钟</Text>
                      </div>
                    )}
                    {selectedInteraction.messageCount && (
                      <div>
                        <Text strong>消息数量：</Text>
                        <Text>{selectedInteraction.messageCount} 条</Text>
                      </div>
                    )}
                  </Space>
                </Card>
              </Col>
              
              <Col span={12}>
                <Card title="互动时间线" size="small">
                  <Timeline
                    size="small"
                    items={generateTimelineData(selectedInteraction)}
                  />
                </Card>
              </Col>
            </Row>

            <Card title="互动内容" size="small" style={{ marginTop: '16px' }}>
              <Text>{selectedInteraction.content}</Text>
            </Card>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default InteractionRecordPage;